package org.hot100_0.leetcode3;

import java.util.HashMap;
import java.util.HashSet;

public class Solution {
    public static void main(String[] args) {
        int length = lengthOfLongestSubstring2("abcabcbb");
        System.out.println(length);
    }

    public static int lengthOfLongestSubstring2(String s) {

        int n = s.length();

        HashSet<Character> hashSet = new HashSet<>();

        int left = 0;
        int right = -1;

        int ans = 1;
        for (int i = left; i < n; i++) {
            if (i != 0) {
                hashSet.remove(s.charAt(i - 1));
            }

            while (right + 1 < n && !hashSet.contains(s.charAt(right + 1))) {
                hashSet.add(s.charAt(right + 1));
                right++;
            }

            ans = Math.max(ans, right - i + 1);
        }

        return ans;
    }

    public static int lengthOfLongestSubstring(String s) {

        HashSet<Character> hashSet = new HashSet<>();

        int n = s.length();

        if (n == 1 || n == 0) {
            return n;
        }

        int maxLength = 1;
        for (int i = 0; i < n; i++) {
            int length = 0;
            int j = i;
            while (j < n && !hashSet.contains(s.charAt(j))) {
                length++;
                hashSet.add(s.charAt(j));
                j++;
            }
            maxLength = Math.max(maxLength, length);
            hashSet.clear();
        }

        return maxLength;
    }
}
